<template>
    <van-nav-bar left-text="返回" left-arrow @click-left="onClickLeft" @click-right="onClickRight" fixed>
        <template #title>
            <van-search @search="onSearch" v-model="sousuo" placeholder="请输入搜索关键词" />
        </template>
        <template #right>
            <van-cell @click="showPopup">
                <template #title>
                    <van-icon name="list-switching" size="35" />
                </template>
            </van-cell>
        </template>
    </van-nav-bar>
    <div style="height: 50px;"></div>
    <van-popup v-model:show="showLeft" position="left" :style="{ width: '30%', height: '100%' }">
        <van-tree-select height="100vh" style="width:100vw" v-model:main-active-index="activeIndex" :items="TypeList"
            @click-nav="onType">
        </van-tree-select>
    </van-popup>

    <van-dropdown-menu>
        <van-dropdown-item v-model="flag" @change="flagebian" :options="flagdata" />
        <van-dropdown-item v-model="flags" @change="flagesbian" :options="flagsdata" />
    </van-dropdown-menu>
    <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
        <van-list v-model:loading="loading" :finished="finished" finished-text="已经到头了！" @load="onLoad">
            <div class="mainWarp" style="background:#f3f3f3">
                <ul class="proul">
                    <RouterLink v-for="item in typedata" :key="item.id" :to="{path: '/product/product/info',query: { id: item.id }}">
                        <li>
                            <img v-if="item.thumbs_cdn && item.thumbs_cdn.length > 0" :src="item.thumbs_cdn[0]" />
                            <p class="tit">{{ item.name }}</p>
                            <div class="price">
                                <p>￥{{ item.price }}<span style="text-decoration: none;">库存：{{ item.stock }}</span></p>
                            </div>
                        </li>
                    </RouterLink>
                </ul>
            </div>
        </van-list>
    </van-pull-refresh>
</template>
<script setup>
import { ref, getCurrentInstance, reactive, watchEffect ,onMounted } from 'vue';
import { RouterLink } from 'vue-router';
const { proxy } = getCurrentInstance();
const showLeft = ref(false);
const flag = ref(0);
const flags = ref('a');
const typeid = ref(proxy.$route.query.id);
//判断下拉刷新状态
const refreshing = ref(false);
//懒加载状态
const loading = ref(false);
//是否下拉加载
const finished = ref(false);
//第几页
const page = ref(1);
//每一页显示的商品数量
const limit = ref(10);
//获取商品数据
const typedata = reactive([]);
//数据总数
const typeCount = ref(0);
const flagbian1 = ref(0);
const flagbian2 = ref(1);
//选中的索引
const activeIndex = ref(0);
//定义数据
const TypeList = reactive([{ text: '全部分类商品', id: 0 }]);
//搜索
const sousuo = ref('');
//接收首页的值
const sousuos = ref(proxy.$route.query.keyword || '');
// 数据是否已加载的标志
const dataLoaded = ref(false);

onMounted(()=>{
    if (sousuos.value && !dataLoaded.value) {
        onSearch(sousuos.value);
    }
})
//搜索的方法
const onSearch = (values) => {
    onRefresh();
    if (!dataLoaded.value) {
        sousuo.value = values;
        getProductData();
        // 设置数据为已加载
        dataLoaded.value = true;
    }
}

//下拉刷新
const onRefresh = () => {
    refreshing.value = true;
    loading.value = true;
    page.value = 1;
    typedata.length = 0;
    dataLoaded.value = false;
    onLoad();
}

//上拉刷新
const onLoad = () => {
    if (!refreshing.value && typedata.length < typeCount.value) {
        page.value = page.value + 1;
    }

    if (refreshing.value) {
        setTimeout(() => {
            refreshing.value = false;
        }, 1500);
    }
    setTimeout(getProductData, 1500);
};


const flagebian = (values) => {
    flagbian1.value = values;
    getProductData();
    typedata.length = 0;
}

const flagesbian = (values) => {
    flagbian2.value = values;
    getProductData();
    typedata.length = 0;
}
const getProductData = async () => {
    // typedata.length = 0;
    // 检查数据是否已加载，防止重复加载
    if (dataLoaded.value) return;
    let data = {
        typeid: typeid.value,
        page: page.value,
        limit: limit.value,
        flag: flagbian1.value,
        flags: flagbian2.value,
        sousuo: sousuo.value
    }
    let result = await proxy.$Api.productData(data);
    if (result && result.code === 1) {
        finished.value = false;
        loading.value = false;

        typeCount.value = result.data.typeCount;
        typedata.push(...result.data.typedata);

        if (typedata.length === typeCount.value) {
            finished.value = true;
            loading.value = false;
            return;
        }
    } else {
        finished.value = true;

        return;
    }
}


const flagdata = [
    { text: '全部商品', value: 0 },
    { text: '新品商品', value: 1 },
    { text: '热销商品', value: 2 },
    { text: '推荐商品', value: 3 },
];
const flagsdata = [
    { text: '默认排序', value: 'a' },
    { text: '价格大到小', value: 'b' },
    { text: '价格小到大', value: 'c' },
    { text: '库存排序', value: 'd' }
];

//左边按钮
const onClickLeft = () => {
    proxy.$router.back();
};
//右边按钮弹出框
const showPopup = () => {
    sousuo.value = '';
    showLeft.value = true;
};
//右边按钮
const onClickRight = () => {
    getTypeData();
};

const onType = (index) => {
    typeid.value = TypeList[index].id;
    onRefresh();
}
const getTypeData = async () => {
    let result = await proxy.$Api.TableIndex();

    if (result && result.code === 1) {
        // 重置分类列表
        TypeList.length = 1; // 保留'全部分类商品'

        // 添加从服务器获取的分类数据到TypeList
        for (let item of result.data) {
            TypeList.push({
                text: item.name,
                id: item.id
            });
        }

        // 查找typeid在TypeList中的index
        const indexToSelect = TypeList.findIndex(item => item.id == typeid.value);
        if (indexToSelect >= 0) {
            // 找到匹配项，设置activeIndex为该项的索引
            activeIndex.value = indexToSelect;
        } else {
            // 未找到匹配项，默认选择第一个
            activeIndex.value = 0;
        }
    }
}

watchEffect(() => {
    // 每次typeid变化时尝试匹配TypeList中的id，并更新activeIndex
    const indexToSelect = TypeList.findIndex(item => item.id == typeid.value);
    if (indexToSelect >= 0) {
        activeIndex.value = indexToSelect;
    } else {
        activeIndex.value = 0;
    }
});
</script>
<style scoped>
@import url('/public/assets/css/style.css');
</style>